package com.shike.hq.security;

import com.shike.hq.entity.Admin;
import com.shike.hq.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

// 增加UserDetailsService接口实现类，获取用户的信息
@Service
public class AdminUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("AdminUserDetailsService.loadUserByUsername");
        // 1.查询用户
        Admin admin = adminMapper.selectAdminByUsername(username);
        if (admin == null){
            throw new UsernameNotFoundException("用户" + username + "不存在");
        }
        // 2.设置角色
        // 可以用AuthorityUtils.commaSeparatedStringToAuthorityList，该方法是SpringSecurity提供的，
        // 用于将逗号隔开的权限集字符串切割成可用权限对象列表
        admin.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(admin.getRole()));
        System.out.println(admin);
        return admin;
    }
}
